

/**
 * @description 列表页的order排序
 * 图标：
 * 1. 降序 通用
 * 2. 顺序 通用
 * 3. 收藏 
 * 4. 点赞
 * 5. 价格
 * 6. 点击量 / 浏览时长 
 */

import { useEffect, useMemo, useState } from "react"
import { Button } from "antd"
import AbIcon from "@/components/DecorateIcons/Ab_Icon"

function ListSort({ base }) {

  const [orderData, setOrderData] = useState({
    key: '',
    order: 'desc'
  })
  const [list, setList] = useState([])

  let handleClick = (item) => {
    let key = item.key
    let newOrder = ''

    if (orderData.key !== key) {

      // 切换了排序的key，默认从降序开始
      newOrder = 'desc'
    } else {
      // 同一key，但order需要切换，降序desc -> 升序asc -> 不排序

      switch (orderData.order) {
        case 'desc':
          newOrder = 'asc'
          break;

        case 'asc':
          newOrder = ''
          break;

        case '':
          newOrder = 'desc'
          break;
      }

    }

    // 修改当前排序状态
    setOrderData({
      key: key,
      order: newOrder
    })

    // 修改列表状态
    setList((curList) => {
      // 修改 icon
      return curList.map(item => {
        if (item.key === key) {
          // 降序icon | 顺序icon | 原来icon
          let iconKey = newOrder ? newOrder + '_icon' : item.key + '_icon'
          return {
            ...item,
            icon: base[iconKey]
          }
        } else {
          return {
            ...item,
            // 恢复 原来icon
            icon: base[item.key + '_icon']
          }
        }
      })
    })
  }

  useEffect(() => {
    let newList = [
      {
        key: 'price',
        className: 'price',
        icon: base.price_icon,
        text: base.price_text,
      },
      {
        key: 'thumbsupnum',
        className: 'thumbsupnum',
        icon: base.thumbsupnum_icon,
        text: base.thumbsupnum_text,
      },
      {
        key: 'storeupnum',
        className: 'storeupnum',
        icon: base.storeupnum_icon,
        text: base.storeupnum_text,
      },
      {
        key: 'clicknum',
        className: 'clicknum',
        icon: base.clicknum_icon,
        text: base.clicknum_text,
      },
      {
        key: 'browseduration',
        className: 'browseduration',
        icon: base.browseduration_icon,
        text: base.browseduration_text,
      },
    ]

    // 是否有排序状态
    let { key, order } = orderData
    if (key && order) {
      newList.some(item => {
        if (item.key === key) {
          item.icon = base[order + '_icon']
          return true
        }
      })
    }

    setList(newList)
  }, [base])


  return (
    <div className='sort'>
      {
        list.map(item => (
          <Button
            key={item.key}
            className={`common ${item.className} ${item.key === orderData.key && orderData.order ? 'active' : ''}`}
            icon={<AbIcon className='icon' iconName={item.icon} />}
            onClick={() => handleClick(item)}>
            {item.text}
          </Button>
        ))
      }
    </div>
  )
}
export default ListSort